﻿#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QMouseEvent>
#include <QStatusBar>

MainWindow::MainWindow(int width, int height, QWidget *parent) :
    QMainWindow(parent,Qt::Window|Qt::FramelessWindowHint
#ifdef Q_OS_WIN
                |Qt::WindowSystemMenuHint|Qt::WindowMinimizeButtonHint
#endif
                ),
    defaultSize(width, height), moveWidget(false)
{
    statusBar()->setMaximumHeight(4);
}

void MainWindow::button_max_clicked()
{
    bool ismax = isMaximized()|| isFullScreen();
    if(ismax)
    {
        //窗口化
        showNormal();
        setSize(defaultSize);
    }
    else
    {
        //最大化
        showMaximized();
    }
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    if (e->buttons() == Qt::LeftButton && !(isMaximized() || isFullScreen()))
    {
        moveWidget = true;
        dragPosition = e->globalPos() - frameGeometry().topLeft();
    }
    else
        moveWidget = false;
    e->accept();
}

void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
    if(isMaximized() || isFullScreen())
    {
        moveWidget = false;
        e->accept();
        return;
    }
    if(e->buttons() != Qt::LeftButton)
        moveWidget = false;
    if (moveWidget)
        move(e->globalPos() - dragPosition);
    e->accept();
}

void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
    moveWidget = false;
    e->accept();
}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *e)
{
    moveWidget = false;
    if(isTitle(e->pos()))
        button_max_clicked();
    e->accept();
}

void MainWindow::changeEvent(QEvent *event)
{
    if(event->type()==QEvent::WindowStateChange)
    {
        Qt::WindowStates state = windowState();
        bool ismax = state.testFlag(Qt::WindowMaximized) | state.testFlag(Qt::WindowFullScreen);
        bool ismin = state.testFlag(Qt::WindowMinimized);
        if(ismax||ismin)
            moveWidget = false;
        if (ismin)
            handleWindowMinimized();
        else
            setMaximizeButton(ismax);
    }
    QMainWindow::changeEvent(event);
}

void MainWindow::handleWindowMinimized()
{
}

void MainWindow::setSize(const QSize &size)
{
    QRect rect;
    QRect screen = QApplication::desktop()->availableGeometry(this);
    rect.setWidth(qMin(size.width(),screen.width()));
    rect.setHeight(qMin(size.height(),screen.height()));
    rect.moveCenter(screen.center());
    setGeometry(rect);
}
